/**
 * Created by Administrator on 2017/7/14.
 */
import axios from 'axios'
import {Toast} from 'mint-ui';
import store from 'store';
var urlConfig = require('../../../src/config');

function regtoken(url){
  var date = url.match(/\?api_token=(.*)/) || [];
  return date[1] || false;
}

let token=regtoken(window.location.href);
let url = urlConfig.ajaxUrl;
let config = {
  method: 'get',
  baseURL: url,
};

var httpAjax = axios.create(config);
/*
if(/artqiyi/.test(location.href)){
  httpAjax.defaults.headers.common["Authorization"]="Bearer "+store.get('apiToken');
}*/
if(token == null || token == "undefined" || token== "" ||token == undefined || token == "null"){
  httpAjax.defaults.headers.common["Authorization"] = "Bearer "+store.get('apiToken');
  httpAjax.interceptors.request.use((config) => {
    if (config.headers.common.Authorization == "Bearer undefined") {
      config.headers.common.Authorization = "Bearer " + store.get('apiToken');
    }
    return config;
  }, () => {
    return config;
  });
}else{
  httpAjax.defaults.headers.common["Authorization"] = "Bearer "+token;
  httpAjax.interceptors.request.use((config) => {
    if (config.headers.common.Authorization == "Bearer undefined") {
      config.headers.common.Authorization = "Bearer " + token;
    }
    return config;
  }, () => {
    return config;
  });
}

//返回状态判断// 添加响应拦截器
httpAjax.interceptors.response.use((res) => {
  if ((200 <= res.status && res.status < 300) && res.status != 204) {
    return res.data;
  } else if (res.status == 401) {
    //重新登录
    Toast({
      message: '登录超时，请重新登录',
      iconClass: 'mint-toast-icon mintui mintui-field-warning'
    });
  } else {
    Toast({
      message: res.data.message,
      iconClass: 'mint-toast-icon mintui mintui-field-error'
    });
    return Promise.reject(res.data);
  }
}, (error) => {
  // 对响应错误做点什么
  return Promise.reject(error);
});

//接口列表
export default {
  fetch: (url, config) => {
    return new Promise((resolve, reject) => {
      httpAjax(url, config)
        .then(response => {
          resolve(response);
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
}
